#include "Unique.h"

using namespace std;

int ExtractUnique(char* fname)
{
    map<string,UniqueSeqs> Data;
    char dummy[MAX_LINE];
	string Sequence, SequenceID, temp;
	unsigned int i = 0, len = 0, lentotal = 0, num_seq=0;
	fstream InputSeq;
	InputSeq.open(fname);
	if(InputSeq.fail())
	{
	   cout<<"Cannot open "<<fname<<endl;
	   return 0;
    }
    	
	while(!InputSeq.eof())    
    {
        InputSeq.getline(dummy, MAX_LINE);
        if(dummy[0]=='>')
            num_seq++;
    }
	
	cout<<"num_seq = "<<num_seq<<endl;
    InputSeq.clear();   
    InputSeq.seekg(0,ios::beg);	

	InputSeq.getline(dummy, MAX_LINE); /* Read first line */
	for(i = 0; i < num_seq; i++)
    {
		if(dummy[0] == '>')
        {
            len = strlen(dummy);
            len += (dummy[len-1] == '\n')? -1:0;
            SequenceID.assign(dummy, len);
            InputSeq.getline(dummy, MAX_LINE);        
			while(dummy[0]!='>')
            {               
                len = strlen(dummy);
                len += (dummy[len-1] == '\n')? -1:0;
                temp.assign(dummy, len);
                Sequence+=temp;
                if(!InputSeq.eof())
                    InputSeq.getline(dummy, MAX_LINE);
                else
                    break;
            }           
		}
		map<string,UniqueSeqs>::iterator it = Data.find(Sequence);
		if (it == Data.end())
        { 	//it's unique.
		    Data[Sequence].Name = SequenceID;
            Data[Sequence].Sequences = Sequence;  
		    Data[Sequence].Members = SequenceID;
		    Data[Sequence].Size = 1;
        }
        else 
        {  // its a duplicate.
            Data[Sequence].Members += "," + SequenceID;
	        Data[Sequence].Size++;
		}
        Sequence.clear(); 			
	}
	InputSeq.close();
	//output unique sequences
    fstream OutputSeq1,OutputSeq2;
    string temponame1(fname);
    string temponame2;
    temponame1+=".unique";
    temponame2=temponame1+".list";
    OutputSeq1.open(temponame1.c_str(), ios_base::out);
    OutputSeq2.open(temponame2.c_str(), ios_base::out);
    if(OutputSeq1.fail())
    {
        cout<<"Can not open output file "<<temponame1<<endl;
        return 0;
    }
    if(OutputSeq2.fail())
    {
        cout<<"Can not open output file "<<temponame2<<endl;
        return 0;
    }
    map<string,UniqueSeqs>::iterator it = Data.begin();
    OutputSeq2<<num_seq<<endl;
    while(it!=Data.end())
    {
        OutputSeq1<<(*it).second.Name<<endl;
        OutputSeq1<<(*it).second.Sequences<<endl;
        OutputSeq1<<(*it).second.Size<<endl;
        OutputSeq2<<(*it).second.Name<<endl;
        OutputSeq2<<(*it).second.Members<<endl;
        it++;
    }
    OutputSeq1.close();
    OutputSeq2.close();
    num_seq=Data.size();
    Data.empty();
    cout<<"extracting unique sequences done"<<endl;
	return num_seq;    
}
